package com.example.javarabbitmq;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 服务日志消费者客户端示例。也可以使用Logstash实现日志的监控处理。
 * @author HAN Bing
 * @date 2021/6/1
 */
public class ReceiveLog {
    private static final String IP_ADDRESS = "8.131.233.42";
    private static final int PORT = 5672;

    public static void main(String[] args) throws IOException, TimeoutException {
        Address[] addresses = new Address[]{new Address(IP_ADDRESS, PORT)};
        ConnectionFactory factory = new ConnectionFactory();
        factory.setUsername("root");
        factory.setPassword("d");
        Connection connection = factory.newConnection(addresses);

        try {
            Channel channelDebug = connection.createChannel();
            Channel channelInfo = connection.createChannel();
            Channel channelWarn = connection.createChannel();
            Channel channelError = connection.createChannel();
            // 省略channel.BasicQos
            channelDebug.basicConsume("queue.debug", false, "DEBUG", new ConsumerThread(channelDebug));
            channelDebug.basicConsume("queue.info", false, "INFO", new ConsumerThread(channelInfo));
            channelDebug.basicConsume("queue.warning", false, "WARNING", new ConsumerThread(channelWarn));
            channelDebug.basicConsume("queue.error", false, "ERROR", new ConsumerThread(channelError));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static class ConsumerThread extends DefaultConsumer {
        public ConsumerThread(Channel channel) {
            super(channel);
        }
        @Override
        public void handleDelivery(String consumerTag, Envelope envelope,
                                    AMQP.BasicProperties properties,
                                    byte[] body) throws IOException {
            String log = new String(body);
            // 打印内容的样例：=ERROR REPORT====
            System.out.println("=" + consumerTag + " Report====\n" + log);
            // 发送Ack
            getChannel().basicAck(envelope.getDeliveryTag(), false);
        }
    }
}
